<template>
  <div class="together-create-view">
    <!-- 顶部栏 -->
    <van-nav-bar title="创建小天地" left-text="返回" left-arrow @click-left="goBack" />
    <p class="subtitle">和好友打造共同生活的小天地</p>

    <!-- 选择好友 -->
    <section class="section">
      <div class="section-label">选择好友</div>

      <div class="select-bar">
        <div class="avatars avatars-scroll">
          <template v-if="selectedFriends.length">
            <div v-for="f in selectedFriends" :key="f.id" class="avatar-preview">
              <van-image :src="f.avatar" width="44" height="44" round />
            </div>
          </template>
          <template v-else>
            <div class="avatar-preview"></div>
          </template>
        </div>

        <van-dropdown-menu>
          <van-dropdown-item v-model:show="friendDropShow" :title="friendDropTitle">
            <div class="friend-dropdown">
              <van-checkbox-group v-model="selectedIds">
                <van-cell-group inset>
                  <van-cell v-for="f in ohterfriends" :key="f.id" clickable @click="onToggleCheck(f.id)" :border="true"
                    class="friend-cell">
                    <template #icon>
                      <van-checkbox :name="f.id" shape="square" checked-color="#BF4F1D" @click.stop
                        class="friend-check" />
                    </template>
                    <template #title>
                      <div class="friend-line">
                        <van-image :src="f.avatar" width="30" height="30" round />
                        <span class="friend-name">{{ f.name }}</span>
                      </div>
                    </template>
                  </van-cell>
                </van-cell-group>
              </van-checkbox-group>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>
      </div>
    </section>

    <!-- 标题输入 -->
    <van-cell-group inset>
      <van-field v-model.trim="form.title" label="制作小天地" placeholder="给你们的小天地取个名字吧" clearable />
    </van-cell-group>

    <!-- 文案 + 开工 -->
    <section class="card">
      <van-field v-model="form.caption" type="textarea" rows="3" :autosize="{ minHeight: 70, maxHeight: 160 }"
        :placeholder="placeholder" />
      <div class="card-actions">
        <div class="bg-selector">
          <div class="bg-icon-1" @click="onBgClick">
            <van-icon name="edit" size="18" />
          </div>
          <div class="bg-icon-2" @click="onBgClick">
            <van-icon name="photo" size="18" />
          </div>
          <input type="file" ref="bgInput" accept="image/*" style="display: none" @change="onBgChange">
        </div>

        <van-button size="small" :loading="isGenerating" :disabled="!canStart" @click="onStartBuild">
          开工
        </van-button>
      </div>
    </section>

    <!-- 轻量 Loading 条 -->
    <transition name="fade">
      <div v-if="isGenerating" class="gen-strip" role="status" aria-live="polite">
        <van-loading size="18px" />
        <span>正在生成方案，请稍等片刻…</span>
      </div>
    </transition>

    <!-- 方案选择卡片 -->
    <section v-if="stage === 'planning'" class="plan-card">
      <div class="plan-header">
        <span>建造完成！请选择下方中的一个，或选择</span>
        <a class="link" @click="regeneratePlans">重新生成</a>
      </div>

      <div class="plan-rows">
        <div class="plan-item">
          <img :src="housePlans[0]?.src" alt="方案一" />
        </div>
        <div class="plan-item">
          <img :src="housePlans[1]?.src" alt="方案二" />
        </div>
      </div>

      <van-radio-group v-model="selectedPlanId" direction="horizontal" class="plan-radios">
        <van-radio name="A" checked-color="#BF4F1D">方案一</van-radio>
        <van-radio name="B" checked-color="#BF4F1D">方案二</van-radio>
      </van-radio-group>

      <div class="plan-actions">
        <van-button size="small" @click="confirmPlan">就要这个</van-button>
      </div>
    </section>

    <!-- 画布 -->
    <section v-if="stage !== 'idle'" class="canvas-section">
      <div class="canvas" ref="canvasRef">
        <img v-if="backgroundUrl" class="bg" :src="backgroundUrl" alt="背景图" />
        <HousePlaceholder v-else class="bg" />

        <div v-for="(s, idx) in stickers" :key="s.id" class="sticker" :style="{ left: s.x + 'px', top: s.y + 'px' }"
          @pointerdown.prevent="startDrag(idx, $event)">
          <van-image v-if="s.src" :src="s.src" width="50" height="80" fit="cover" />
          <div v-else class="stub big" />
        </div>
      </div>
    </section>

    <!-- 拖拽提示 & 头像池 -->
    <section v-if="stage === 'arrange'" class="drag-hint">拖动下方形象，可以将好友摆在图中哦</section>
    <section v-if="stage === 'arrange'" class="sticker-pool">
      <div v-for="(src, i) in poolSources" :key="i" class="pool-item" @pointerdown="startPoolDrag(src, $event)"
        @click.stop="addStickerAtCenter(src)">
        <van-image v-if="src" :src="src" width="50" height="80" fit="cover" />
        <div v-else class="stub" />
      </div>
    </section>

    <section v-if="stage === 'arrange'" class="confirm-wrap">
      <!-- 原来是直接 router.push，这里换成 confirmAndGo：先新增卡片，再跳转，逻辑效果不变 -->
      <van-button type="primary" block @click="confirmAndGo"> 确认选择 </van-button>
    </section>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onBeforeUnmount } from 'vue'
import { Toast } from 'vant'
import { useRouter } from 'vue-router'
import HousePlaceholder from '../components/HousePlaceholder.vue'
import { useTogetherStore } from '@/stores/together'   // ⭐ 新增：引入卡片仓库

const router = useRouter()
const togetherStore = useTogetherStore()               // ⭐ 新增：实例化

/** 阶段：idle -> planning -> arrange */
type Stage = 'idle' | 'planning' | 'arrange'
const stage = ref<Stage>('idle')

/** 生成中 */
const isGenerating = ref(false)
let genTimer: number | undefined

/** 文案占位 */
const placeholder = '描述小天地的外观吧'

/** 表单 */
const form = reactive({ title: '', caption: '' })
const appliedCaption = ref('')

/** “开工”按钮可用 */
const canStart = computed(() => form.caption.trim().length > 0 && !isGenerating.value)

/** 画布 */
const canvasRef = ref<HTMLDivElement | null>(null)
const backgroundUrl = ref<string>('')

/** 贴纸（头像） */
interface Sticker { id: string; src: string; x: number; y: number }
const stickers = ref<Sticker[]>([])
let draggingIndex = -1
let draggingEl: HTMLElement | null = null
let dragStartX = 0
let dragStartY = 0
let pointerStartX = 0
let pointerStartY = 0
let rafId = 0
let pendingDX = 0
let pendingDY = 0
let animating = false

/** 好友数据 */
const friends = ref([
  { id: 'u5', name: '主角', avatar: '/chat/role_zhujue_head.png' , body: '/chat/touming_zhujue.png'},
  { id: 'u1', name: '陈茜', avatar: '/chat/role_hushinv_head.png' , body: '/chat/touming_baimaonv.png'},
  { id: 'u2', name: '鸡毛', avatar: '/chat/role_boy_friend_bg.png' , body: '/chat/touming_boy_friend.png'},
  { id: 'u3', name: '江秋月', avatar: '/chat/role_jichenv_head.png' , body: '/chat/touming_jichenv.png'},
  { id: 'u4', name: '张泽', avatar: '/chat/role_baimaonan_head.png' , body: '/chat/touming_maozinan.png'},
/*   { id: 'u5', name: '李梦蝶', avatar: '/chat/role_zhujue_head.png' }, */
])

const ohterfriends = ref([
  { id: 'u1', name: '陈茜', avatar: '/chat/role_hushinv_head.png' , body: '/chat/touming_baimaonv.png'},
  { id: 'u2', name: '鸡毛', avatar: '/chat/role_boy_friend_bg.png' , body: '/chat/touming_boy_friend.png'},
  { id: 'u3', name: '江秋月', avatar: '/chat/role_jichenv_head.png' , body: '/chat/touming_jichenv.png'},
  { id: 'u4', name: '张泽', avatar: '/chat/role_baimaonan_head.png' , body: '/chat/touming_maozinan.png'},
/*   { id: 'u5', name: '李梦蝶', avatar: '/chat/role_zhujue_head.png' }, */
])

/** 多选下拉 */
const friendDropShow = ref(false)
const selectedIds = ref<string[]>([])
const friendDropTitle = computed(() =>
  selectedIds.value.length ? `已选 ${selectedIds.value.length} 位` : '选择好友'
)
const selectedFriends = computed(() =>
  selectedIds.value.map(id => friends.value.find(f => f.id === id)!).filter(Boolean)
)
function onToggleCheck(id: string) {
  const set = new Set(selectedIds.value)
  set.has(id) ? set.delete(id) : set.add(id)
  selectedIds.value = Array.from(set)
}
const DEFAULT_SOURCE =  '/chat/touming_zhujue.png' ;

const poolSources = computed<any[]>(() => [
  DEFAULT_SOURCE,
  ...selectedFriends.value.map(p => p.body).filter(Boolean),
])

const bgInput = ref<HTMLInputElement | null>(null)

function onBgClick() {
  bgInput.value?.click()
}

function onBgChange(e: Event) {
  const input = e.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const reader = new FileReader()
    reader.onload = () => (backgroundUrl.value = reader.result as string)
    reader.readAsDataURL(input.files[0])
  }
}

/** 开工 -> 进入方案选择 */
function onStartBuild() {
  appliedCaption.value = form.caption.trim()
  if (!appliedCaption.value) {
    Toast('先简单描述一下小天地吧～')
    return
  }
  if (isGenerating.value) return
  isGenerating.value = true

  const delay = 1600 + Math.floor(Math.random() * 1000)
  window.clearTimeout(genTimer)
  genTimer = window.setTimeout(() => {
    housePlans.value = [
      { id: 'A', src: '/together/together_1_1.png' },
      { id: 'B', src: '/together/together_1_2.png' }
    ]
    selectedPlanId.value = ''
    stage.value = 'planning'
    isGenerating.value = false
  }, delay)
}

/** 方案选择数据 */
const housePlans = ref<{ id: 'A' | 'B'; src: string }[]>([])
const selectedPlanId = ref<'A' | 'B' | ''>('')

function regeneratePlans() {
  const salt = `?t=${Date.now()}`
  housePlans.value = [
    { id: 'A', src: '/chat/house_plan_a.png' + salt },
    { id: 'B', src: '/chat/house_plan_b.png' + salt }
  ]
  selectedPlanId.value = ''
}

function confirmPlan() {
  if (!selectedPlanId.value) {
    Toast('请选择一个方案')
    return
  }
  const picked = housePlans.value.find(p => p.id === selectedPlanId.value)
  if (!picked) return
  backgroundUrl.value = picked.src
  stage.value = 'arrange'
  Toast('已应用所选方案，开始布置吧！')
}

/** 从头像池拖拽到画布 */
let ghostEl: HTMLElement | null = null
let ghostSrc = ''
let ghostAnimating = false
let ghostNextX = 0
let ghostNextY = 0
function startPoolDrag(src: string, e: PointerEvent) {
  ghostSrc = src
  ghostEl = document.createElement('div')
  ghostEl.className = 'drag-ghost'
  document.body.appendChild(ghostEl)
  ghostEl.innerHTML = `<img src="${src}" />`
  ghostNextX = e.clientX - 36
  ghostNextY = e.clientY - 36
  ghostEl.style.left = `${ghostNextX}px`
  ghostEl.style.top = `${ghostNextY}px`
    ; (e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId)
  window.addEventListener('pointermove', onPoolPointerMove, { passive: true })
  window.addEventListener('pointerup', onPoolPointerUp, { once: true })
}
function onPoolPointerMove(e: PointerEvent) {
  if (!ghostEl) return
  ghostNextX = e.clientX - 36
  ghostNextY = e.clientY - 36
  if (!ghostAnimating) {
    ghostAnimating = true
    requestAnimationFrame(() => {
      if (ghostEl) {
        ghostEl.style.left = `${ghostNextX}px`
        ghostEl.style.top = `${ghostNextY}px`
      }
      ghostAnimating = false
    })
  }
}
function onPoolPointerUp(e: PointerEvent) {
  if (!ghostEl) return
  const canvas = canvasRef.value
  if (canvas) {
    const rect = canvas.getBoundingClientRect()
    const inside =
      e.clientX >= rect.left && e.clientX <= rect.right &&
      e.clientY >= rect.top && e.clientY <= rect.bottom
    if (inside) {
      const x = e.clientX - rect.left - 32
      const y = e.clientY - rect.top - 32
      stickers.value.push({ id: crypto.randomUUID(), src: ghostSrc, x, y })
    }
  }
  ghostEl.remove()
  ghostEl = null
  ghostSrc = ''
  window.removeEventListener('pointermove', onPoolPointerMove)
}
function addStickerAtCenter(src: string) {
  const canvas = canvasRef.value
  if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const x = rect.width / 2 - 32
  const y = rect.height / 2 - 32
  stickers.value.push({ id: crypto.randomUUID(), src, x, y })
}

/** 画布内拖动 */
function startDrag(index: number, e: PointerEvent) {
  draggingIndex = index
  draggingEl = e.currentTarget as HTMLElement
  const s = stickers.value[index]
  dragStartX = s.x
  dragStartY = s.y
  pointerStartX = e.clientX
  pointerStartY = e.clientY
  draggingEl.style.transition = 'none'
  draggingEl.style.willChange = 'transform'
    ; (draggingEl as any).setPointerCapture?.(e.pointerId)
  window.addEventListener('pointermove', onStickerPointerMove, { passive: true })
  window.addEventListener('pointerup', onStickerPointerUp, { once: true })
}
function onStickerPointerMove(e: PointerEvent) {
  if (draggingIndex < 0 || !draggingEl) return
  const canvas = canvasRef.value
  if (!canvas) return
  const cRect = canvas.getBoundingClientRect()
  let dx = e.clientX - pointerStartX
  let dy = e.clientY - pointerStartY
  const nx = Math.max(0, Math.min(dragStartX + dx, cRect.width - 64))
  const ny = Math.max(0, Math.min(dragStartY + dy, cRect.height - 64))
  dx = nx - dragStartX
  dy = ny - dragStartY
  pendingDX = dx
  pendingDY = dy
  if (!animating) {
    animating = true
    rafId = requestAnimationFrame(() => {
      if (draggingEl) draggingEl.style.transform = `translate3d(${pendingDX}px, ${pendingDY}px, 0)`
      animating = false
    })
  }
}
function onStickerPointerUp() {
  if (draggingIndex < 0 || !draggingEl) return
  const s = stickers.value[draggingIndex]
  s.x = dragStartX + pendingDX
  s.y = dragStartY + pendingDY
  draggingEl.style.transform = ''
  draggingEl.style.willChange = ''
  draggingEl.style.transition = ''
  cancelAnimationFrame(rafId)
  draggingIndex = -1
  draggingEl = null
  pendingDX = pendingDY = 0
  window.removeEventListener('pointermove', onStickerPointerMove)
}

/** 重置等 */
function resetAll() {
  form.title = ''
  form.caption = ''
  appliedCaption.value = ''
  backgroundUrl.value = ''
  stickers.value = []
  selectedIds.value = []
  stage.value = 'idle'
}
function saveScene() { Toast('已保存当前场景') }
function onPrimaryAction() {
  if (stage.value === 'arrange') {
    router.push('/together')
    return
  }
  Toast('下一步占位：可接入你的流程')
}
function goBack() { history.back() }

/** ⭐ 确认选择：先写入卡片，再跳转 */
function confirmAndGo() {
  // 组装卡片数据；保持与你卡片页字段一致
  const title = form.title.trim() || '好姐妹退休就应该住别墅'
  togetherStore.addCard({
    title,
    image: '/together/together_1.png', // 若无背景，给个占位
    members: 0,  
    updateTime: '刚刚更新',
  })
  router.push('/together')
}

onBeforeUnmount(() => {
  window.removeEventListener('pointermove', onStickerPointerMove)
  window.removeEventListener('pointermove', onPoolPointerMove)
  window.clearTimeout(genTimer)
})
</script>

<style scoped>
* {
  box-sizing: border-box;
}

.together-create-view {
  max-width: 640px;
  margin: 0 auto;
  padding-bottom: 96px;
  color: #222;
}

.subtitle {
  margin: 8px 16px 0;
  color: #b35a24;
  font-size: 12px;
}

/* 轻量 Loading 条 */
.gen-strip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 10px 16px 0;
  padding: 8px 12px;
  background: #fff7f1;
  border: 1px solid #ffe0cc;
  color: #9b4b1d;
  border-radius: 10px;
  font-size: 13px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity .2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.section {
  margin: 14px 16px;
}

.section-label {
  font-size: 15px;
  font-weight: 600;
  margin-bottom: 10px;
}

.select-bar {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
}

.avatars {
  display: flex;
  gap: 12px;
}

.avatar-preview {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  border: 1.5px solid #d2d2d2;
  display: grid;
  place-items: center;
  background: #fff;
}

.stub {
  width: 22px;
  height: 22px;
  border: 2px dashed #c8c8c8;
}

.stub.big {
  width: 80px;
  height: 80px;
  border: 2px dashed #c8c8c8;
  background: #f5f5f5;
}

.friend-dropdown {
  max-height: 360px;
  overflow: auto;
  padding-right: 4px;
}

.friend-cell {
  padding-left: 8px;
}

.friend-check {
  margin-right: 10px;
}

.friend-line {
  display: flex;
  align-items: center;
  gap: 10px;
}

.friend-name {
  font-size: 16px;
  color: #222;
}

.card {
  margin: 14px 16px;
  border: 1px solid #eee;
  border-radius: 12px;
  padding: 10px;
  background: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, .03);
}

.card-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 6px;
  margin-left: 8px;
}

/* 方案选择卡片 */
.plan-card {
  margin: 14px 16px;
  border: 1px solid #eee;
  border-radius: 12px;
  padding: 12px;
  background: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, .03);
}

.plan-header {
  display: flex;
  gap: 6px;
  align-items: baseline;
  margin-bottom: 8px;
  color: #444;
  font-size: 12px;
}

.plan-header .link {
  color: #BF4F1D;
  cursor: pointer;
}

.plan-rows {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-top: 8px;
}

.plan-item {
  background: #fafafa;
  border-radius: 12px;
  padding: 6px;
  border: 1px solid #eee;
  display: grid;
  place-items: center;
}

.plan-item img {
  width: 100%;
  height: 140px;
  object-fit: cover;
  border-radius: 10px;
}

.plan-radios {
  margin: 8px 6px 0;
  display: flex;
  justify-content: space-around;
}

.plan-actions {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}

.canvas-section {
  margin: 16px;
}

.together-create-view :deep(.van-nav-bar .van-nav-bar__title),
.together-create-view :deep(.van-nav-bar .van-nav-bar__text),
.together-create-view :deep(.van-nav-bar .van-icon) {
  color: rgb(0, 0, 0);
}

.canvas {
  position: relative;
  width: 100%;
  aspect-ratio: 16/9;
  border-radius: 12px;
  overflow: hidden;
  background: #f6f7fb;
  border: 1px solid #eee;
}

/* 防止浏览器手势干扰拖拽 */
.canvas,
.sticker,
.pool-item {
  touch-action: none;
}

.canvas .bg {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.sticker {
  position: absolute;
  width: 80px;
  width: 80px;
  cursor: grab;
  user-select: none;
  will-change: transform;
}

.sticker .remove {
  position: absolute;
  right: -10px;
  top: -10px;
}

.caption {
  position: absolute;
  left: 16px;
  bottom: 12px;
  right: 16px;
  text-align: center;
  background: rgba(255, 255, 255, .75);
  padding: 8px 12px;
  border-radius: 12px;
  font-size: 14px;
  color: #333;
  backdrop-filter: blur(4px);
}

.drag-hint {
  margin: 6px 18px;
  color: #666;
  font-size: 14px;
}

.sticker-pool {
  margin: 0 16px 16px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 14px;
}

.pool-item {
  height: 96px;
  border-radius: 12px;
  border: 1px dashed #d5d5d5;
  display: grid;
  place-items: center;
  background: #fafafa;
  overflow: hidden;
}

/* 跟手拖拽浮层 */
.drag-ghost {
  position: fixed;
  width: 72px;
  height: 72px;
  pointer-events: none;
  z-index: 9999;
  transform: translateZ(0);
}

.drag-ghost img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 6px 16px rgba(0, 0, 0, .18);
  border: 2px solid #fff;
}

.house {
  width: 100%;
  height: 100%;
  display: block;
}

/* 控制下拉宽度，避免被内容压缩 */
.select-bar :deep(.van-dropdown-menu) {
  width: 30%;
  display: block;
  min-width: 0;
  border: none;
}

.select-bar :deep(.van-dropdown-menu__bar) {
  box-shadow: none;
}

.bg-selector {
  display: flex;
  gap: 8px;
}

.bg-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 4px;
  cursor: pointer;
}

.bg-icon:hover {
  background: #e8e8e8;
}

.confirm-wrap {
  width: 300px;
  margin: 16px 0 0 30px;
  display: flex;
  justify-content: center;
}
</style>
